package com.ssm.service.impl;

import com.ssm.dao.IRoleDao;
import com.ssm.dao.IUserDao;
import com.ssm.domain.Permission;
import com.ssm.domain.Role;
import com.ssm.domain.UserInfo;
import com.ssm.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Transactional
public class RoleServiceImpl implements IRoleService {

    @Autowired
    private IRoleDao roleDao;

    @Autowired
    private IUserDao userDao;

    @Override
    public List<Role> findRoleByUserId(String userId) throws Exception {
        return roleDao.findById(userId);
    }

    @Override
    public List<Role> findAll() throws Exception {
        return roleDao.findAll();
    }


    @Override
    public void save(Role role) throws Exception {
        //获取所有角色
        List<Role> roleList = roleDao.findAll();
        List<String> roleIds = new ArrayList<>();
        //获取所有角色的id
        for (Role role1:roleList) {
            roleIds.add(role1.getId());
        }
        //找出没出现过的roleId值
        Integer roleId = 1;
        while (roleIds.contains(String.valueOf(roleId))){
            roleId++;
        }
        role.setId(String.valueOf(roleId));
        roleDao.save(role);
    }

    @Override
    public void addUserToRole(String[] userIds, String roleId) {
        for (String userId:userIds) {
            roleDao.addUserToRole(userId, roleId);
        }
    }

    @Override
    public Role findByRoleId(String roleId) {
        return roleDao.findByRoleId(roleId);
    }

    @Override
    public List<UserInfo> findOtherUsers(String roleId) {
        return userDao.findOtherUsers(roleId);
    }

    @Override
    public void deleteById(String id) {
        roleDao.deleteById(id);
    }

    @Override
    public Map<String,List> findRoleInfoById(String id) {
        Map<String,List> roleInfo = new HashMap<>();
        List<UserInfo> users = roleDao.findUserById(id);
        List<Permission> permissions = roleDao.findPermissionById(id);
        roleInfo.put("users", users);
        roleInfo.put("permissions", permissions);
        return roleInfo;
    }
}
